package com.explorati.LeetCode129.sumNumbers;

/**
 * @ Author : Weijian_Wang
 * @ Date : Created in 21:06 2020/10/29 0029
 * @ Description ：
 */
public class Solution {

    public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }

    /**
     * 给定一个二叉树，它的每个结点都存放一个 0-9 的数字，每条从根到叶子节点的路径都代表一个数字。
     *
     * 例如，从根到叶子节点路径 1->2->3 代表数字 123。
     *
     * @param root
     * @return
     */
    public int sumNumbers(TreeNode root) {
        return sumNumbers(root, 0);
    }

    private int sumNumbers(TreeNode root, int preSum) {
        if(root == null) {
            return 0;
        }

        int res = root.val + preSum * 10;
        if(root.left == null && root.right == null) {
            return res;
        }else {
            return sumNumbers(root.left, res) + sumNumbers(root.right, res);
        }
    }
}
